package com.realbrand.net.realbrandpay.ui.activity.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IUserInfo;
import com.realbrand.net.realbrandpay.ui.activity.SetPersonImageActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/7/4.
 */

public class DatumActivity extends BaseActivity {
    @BindView(R.id.tv_datum_useName)
    TextView tvDatumUseName;
    @BindView(R.id.et_datum_useName)
    EditText etDatumUseName;
    @BindView(R.id.datum_iv_true)
    ImageView datumIvTrue;
    @BindView(R.id.tv_datum_useNameMistake)
    TextView tvDatumUseNameMistake;
    @BindView(R.id.et_datum_password)
    EditText etDatumPassword;
    @BindView(R.id.et_datum_passwordAgain)
    EditText etDatumPasswordAgain;
    @BindView(R.id.bt_datum_sumbit)
    Button btDatumSumbit;
    @BindView(R.id.datumactivity_toolbar)
    Toolbar datumactivityToolbar;
    @BindView(R.id.civ_datum_tuXiang)
    CircleImageView civDatumTuXiang;

    public static final int DATUM_CODE = 0x0001;
    @BindView(R.id.et_datum_pay_password)
    EditText etDatumPayPassword;
    @BindView(R.id.et_datum_pay_passwordAgain)
    EditText etDatumPayPasswordAgain;
    //用户上传的图像
    private Bitmap bitmap;
    //用户填写的用户名，密码
    private String userName, password, passwordAgain, payPassword, payPasswordAgain;
    //用户手机号
    private String phone;

    //字符串记性URLEncode编码
    private String encode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        datumactivityToolbar.setTitle("");
        setSupportActionBar(datumactivityToolbar);
        tvDatumUseNameMistake.setVisibility(View.INVISIBLE);
        datumIvTrue.setVisibility(View.INVISIBLE);
        Intent intent = getIntent();
        phone = intent.getStringExtra("UserPhone");
        Log.d("zhu", "收到的手机号码" + phone);
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.datum_activity;
    }

    @Override
    protected void setOnClick() {
        civDatumTuXiang.setOnClickListener(this);
        btDatumSumbit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击提交
            case R.id.bt_datum_sumbit:
                userName = etDatumUseName.getText().toString();
                password = etDatumPassword.getText().toString();
                passwordAgain = etDatumPasswordAgain.getText().toString();
                payPassword = etDatumPayPassword.getText().toString();
                payPasswordAgain = etDatumPayPasswordAgain.getText().toString();
                if (isNull()) {
                    Static.toast(this, "请完善所有资料！");
                } else {
                    if (Static.isLetterDigit(userName) && Static.stringLength(userName)) {
                        if (Static.isLetterDigit(password) && Static.passwdLength(password)) {
                            if (Static.pwLength(payPassword)) {
                                if (password.equals(passwordAgain)) {

                                    if (payPassword.equals(payPasswordAgain)) {
                                        //再提交
                                        sumbit();
                                    } else {
                                        Static.toast(DatumActivity.this, "两次输入的提现密码不一致");
                                    }

                                } else {
                                    Static.toast(DatumActivity.this, "两次输入的密码不一致");
                                }
                            } else {
                                Static.toast(DatumActivity.this, "提现密码有误，请输入6位数字的提现密码");
                            }
                        } else {
                            Static.toast(DatumActivity.this, "登录密码有误，请输入6位以上字母加数字的登录密码");
                        }
                    } else {
                        Static.toast(DatumActivity.this, "用户名有误，请输入6-12位字母加数字的用户名");
                    }
                }
                break;
            //点击上传图像
            case R.id.civ_datum_tuXiang:
                startActivityForResult(new Intent(DatumActivity.this, SetPersonImageActivity.class), DATUM_CODE);
                break;
        }
    }

    /**
     * 提交用户填写的信息
     */
    private void sumbit() {
        //将图像装换成string
        String bitString = Static.bitmapToString(bitmap);
        //将需要插入的参数放到数组里然后装换成字符串
        ArrayList<String> keyList = new ArrayList<>();
        keyList.add("UserAccount");
        keyList.add("UserPasswd");
        keyList.add("UserMobile");
        keyList.add("PayPasswd");
        ArrayList<String> valueList = new ArrayList<>();
        valueList.add(userName);
        valueList.add(password);
        valueList.add(phone);
        valueList.add(payPassword);
        String string = Static.getString(keyList, valueList);
        try {
            encode = URLEncoder.encode(string, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("SOURCE", "DatumActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "UserInfo");
            jsonObject.put("DATA", encode);
            jsonObject.put("UserAvatar", bitString);
            Log.d("zhu", "收到的手机号码" + phone);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IUserInfo iUserInfo = retrofit.create(IUserInfo.class);
            Call<ResponseBody> sumbit = iUserInfo.sumbit(body);
            sumbit.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        //拿到返回结果
                        String result = response.body().string();
                        Log.d("zhu", "提交界面返回的结果" + result.toString());
                        if (result.equals("")) {
                            Static.toast(DatumActivity.this, "网络繁忙");
                        } else {
                            try {
                                JSONObject object = new JSONObject(result);
                                String string1 = object.getString("CREDENTIALS");
                                JSONArray data = object.getJSONArray("DATA");
                                JSONObject json = data.getJSONObject(0);
                                String isSuccess = json.getString("Result");
                                if ("1".equals(isSuccess)) {
                                    //插入成功
                                    datumIvTrue.setVisibility(View.VISIBLE);
                                    tvDatumUseNameMistake.setVisibility(View.GONE);
                                    //表示登录成功
                                    String account = json.getString("UserAccount");
                                    String mobile = json.getString("UserMobile");
                                    String balance = json.getString("UserBalance");
                                    String avatar = json.getString("UserAvatar");
                                    //获取当前时间戳
                                    long time = Static.timeNow();
                                    //存储用户信息
                                    SharedPreferences preferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putString("account", account);
                                    editor.putString("mobile", mobile);
                                    editor.putString("balance", new DecimalFormat("0.00").format(Double.parseDouble(balance)));
                                    editor.putString("avatar", avatar);
                                    editor.putString("userType", "5");
                                    editor.putString("credentials", string1);
                                    editor.putLong("time", time);
                                    editor.commit();
                                    LoginActivity.isLogin = true;
                                    if (LoginActivity.isFormShopCar) {
                                        finish();
                                    } else if (LoginActivity.isFormPick) {
                                        finish();
                                    } else {
                                        startActivity(new Intent(DatumActivity.this, WalletActivity.class));
                                        finish();
                                    }
                                } else if ("用户名重复".equals(isSuccess)) {
                                    //插入失败,用户名已被使用
                                    Static.toast(DatumActivity.this, "用户名已被注册");
                                    tvDatumUseNameMistake.setVisibility(View.VISIBLE);
                                } else if ("用户邮箱重复".equals(isSuccess)) {
                                    Static.toast(DatumActivity.this, "邮箱已被使用");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.d("zhu", "请求失败" + t.toString());
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DATUM_CODE && resultCode == RESULT_OK) {
            bitmap = data.getParcelableExtra("bitmap");
            Drawable drawable = new BitmapDrawable(bitmap);
            civDatumTuXiang.setImageDrawable(drawable);
        }
    }

    public boolean isNull() {
        boolean mBoolean;
        if (bitmap != null && userName != null && password != null && passwordAgain != null && payPassword != null && payPasswordAgain != null) {
            return mBoolean = false;
        } else {
            return mBoolean = true;
        }

    }
}
